package com.add.domain;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.add.util.EmailUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@ToString
@Getter
@Setter
public abstract class Clock {
    static final String DEFAULT_LOCATION = "陕西省 西安市 未央区 111县道 111县 靠近北城驾校";
    static final String URL_HEAD="http://yiban.sust.edu.cn/v4/public/index.php";
    //static final String DEFAULT_TOKEN="fd8b70f5d";
    String name;
    String startTime;
    String endTime;
    int code;

    public  boolean clock(User user) {
        //构建打卡请求
        HttpRequest request = HttpRequest.post(URL_HEAD+"/Index/formtime")
                .contentType("application/x-www-form-urlencoded")
                .charset("utf-8")
                .header(Header.CONNECTION, "keep-alive", true)
                .header("X-Requested-With", "XMLHttpRequest", true)//设置异步
                .timeout(20000);//等待时间

        //获取session
        String session = getSession(user);
        if(session==null)  return false;
        request.header(Header.COOKIE, "PHPSESSID=" + session + ";client=android");

        //获取打卡请求体
        Map<String, Object> requestBody = getClockRequestBody(user);
        request.form(requestBody);

        //获取打卡链接(可能错误)
        Map<String,Object> requestUrl=getClockRequestUrl(user);
        if(requestUrl==null)  return false;
        request.setUrl((String) requestUrl.get("url"));

        //执行请求
        HttpResponse response;
        for (int i = 0; i < 3; i++) {
            try{
                response = request.execute();
            }catch (Exception e){
                StaticLog.error("请求超时");
                return false;
            }
            JSONObject body=JSONUtil.parseObj(response.body());
            System.out.println(body);
            int resCode = (int) body.get("code");
            if (resCode != 1) {
                //已完成打卡
                if(body.get("msg").toString().contains("请勿多次提交")){
                    EmailUtil.send(user.getEmail(),getName() , user.getName()+":打卡已完成\n"+"剩余次数:"+requestUrl.get("score"));
                    return true;
                }else{//验证码错误
                    requestUrl=getClockRequestUrl(user);
                    if(requestUrl==null)  return false;
                    request.setUrl((String) requestUrl.get("url"));
                }
            }else{//打卡成功
                EmailUtil.send(user.getEmail(),getName() , user.getName()+":打卡成功\n"+"剩余次数:"+requestUrl.get("score"));
                return true;
            }

        }
        StaticLog.error("url异常");
        return false;


    }

    abstract Map<String, Object> getClockRequestBody(User user);

    //获取请求地址(方式二)
    Map<String,Object> getClockRequestUrl(User user) {

        JSONObject data= JSONUtil.parseObj(JSONUtil.parseObj(HttpRequest.get(URL_HEAD+"/admin/login/captcha.html").execute().body()).get("data")) ;
        JSONObject reqBody=new JSONObject();
        reqBody.append("token",user.getToken());
        reqBody.append("type","online");
        reqBody.append("uri",data.get("image"));
        JSONObject resBody=JSONUtil.parseObj(HttpRequest.post("http://www.bhshare.cn/imgcode/").form(reqBody).execute().body());
        if((int)resBody.get("code")!=200){
            StaticLog.error("验证码识别异常");
            return null;
        }
        String url=String.format(URL_HEAD+"/Index/formtime/add.html?desgin_id=%s&list_id=12&verify=%s&uniqid=%s", getCode(),resBody.get("data"),data.get("uniqid"));
        Map<String,Object> res=new HashMap<>();
        res.put("url",url);
        res.put("score",resBody.get("times"));
        return res;
    }

//    //获取请求地址(方式一)
//    Map<String,Object> getClockRequestUrl(User user) {
//
//        JSONObject data= JSONUtil.parseObj(JSONUtil.parseObj(HttpRequest.get(URL_HEAD+"/admin/login/captcha.html").execute().body()).get("data")) ;
//        //System.out.println(data);
//        String[] ss=new String[2];
//        ss[0]=data.get("image").toString().split(",")[1];
//        Map<String,Object> map=new HashMap<>();
//        map.put("codetype", 1004);
//        map.put("user", user.getUsername());
//        map.put("pass", user.getPassword());
//        map.put("softid", user.getSoftid());
//        map.put("file_base64",ss[0]);
//        JSONObject query=JSONUtil.parseObj(HttpRequest.post("http://upload.chaojiying.net/Upload/GetScore.php").form(map).execute().body());
//        int err= (int)query.get("err_no");
//        if(err==-1002){
//            StaticLog.error("用户名错误");
//            return null;
//        }
//        if(err==-1003){
//            StaticLog.error("密码错误");
//            return null;
//        }
//        int score= (int) query.get("tifen");
//        if(score<10){
//            StaticLog.error("题分不足");
//            EmailUtil.send(user.getEmail(), getName(), user.getName()+":打卡失败,题分不足");
//            return null;
//        }
//        JSONObject yzm=JSONUtil.parseObj(HttpRequest.post("http://upload.chaojiying.net/Upload/Processing.php").form(map).execute().body());
//        ss[0]= (String) yzm.get("pic_str");
//        ss[1]=data.get("uniqid").toString();
//        String url=String.format(URL_HEAD+"/Index/formtime/add.html?desgin_id=%s&list_id=12&verify=%s&uniqid=%s", getCode(),ss[0],ss[1]);
//        Map<String,Object> res=new HashMap<>();
//        res.put("url",url);
//        res.put("score",score);
//        return res;
//
//    }



    //获取session
    String getSession(User user) {
        try{
            String url = user.getUrl();
            HttpResponse  res= HttpRequest
                    .post(URL_HEAD+url)
                    .disableCookie()
                    .execute();
            String cookie = res.getCookieStr().split(";")[0].split("=")[1];
            return cookie;
        } catch (Exception e) {
            StaticLog.error("url失效");
            return null;
        }

    }

    //判断时间是否在有效时间内
    public boolean validTime(Date date) {
        String now = DateUtil.formatTime(date);
        if (getStartTime().compareTo(now) <= 0 && getEndTime().compareTo(now) >= 0)
            return true;
        return false;
    }

}
